package gonat

import (
	"net"
)

var (
	devices           = make(map[string]NatDevice)
	localIpaddrs      []net.IP
	potentialGateways []net.IP
)

func init() {
	ifaces, err := net.Interfaces()
	if err != nil {
		Log4.Error(err)
	}
	for _, iface := range ifaces {
		ifaddrs, err := iface.Addrs()
		if err != nil {
			Log4.Error(err)
		}
		for _, addr := range ifaddrs {
			if x, ok := addr.(*net.IPNet); ok {
				if lan10.Contains(x.IP) || lan176.Contains(x.IP) || lan192.Contains(x.IP) {
					localIpaddrs = append(localIpaddrs, x.IP)
					ip := x.IP.Mask(x.Mask).To4()
					if ip != nil {
						ip[3] = ip[3] | 0x01
						potentialGateways = append(potentialGateways, ip)
					}
				}
			}
		}
	}
}

// DiscoverDevices ：按照下面顺序搜索，搜索到返回
// 1) upnp
// 2)pmp
func DiscoverDevices() ([]NatDevice, error) {

	var retDevices []NatDevice
	devices, _ := DiscoverDevicesUpnp()
	if devices != nil {
		retDevices = append(retDevices, devices)
		return retDevices, nil
	}
	devicespmp, _ := DiscoverDevicePmp()

	if devicespmp != nil {
		retDevices = append(retDevices, devicespmp)
		return retDevices, nil
	}
	return retDevices, nil
}

var (
	// LAN IP ranges
	_, lan10, _  = net.ParseCIDR("10.0.0.0/8")
	_, lan176, _ = net.ParseCIDR("172.16.0.0/12")
	_, lan192, _ = net.ParseCIDR("192.168.0.0/16")
)
